package com.freecloud.javabasics.thread.result;

import com.freecloud.common.LoggerUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

/**
 * Callable + Future 线程返回值
 * @Author: maomao
 * @Date: 2020-03-04 09:42
 */
public class CallableAndFuture {

    public static void main(String[] args) {
        ExecutorService executor = Executors.newCachedThreadPool();

        AccumulationTask task;
        Future<Integer> result;

        List<Future<Integer>> resultList = new ArrayList<>();
        try {
            Integer sum = 0;

            for(int i = 5;i < 10;i++){
                task = new AccumulationTask(i);
                result = executor.submit(task);

                resultList.add(result);
                //此处使用返回结果会造成线程等待，阻塞主线程
                System.out.println("task运行结果" + result.get());
                sum += result.get();
            }
            executor.shutdown();

            LoggerUtil.split();
            LoggerUtil.println("主线程在执行任务" + sum);

        } catch (Exception e) {
            e.printStackTrace();
        }

        System.out.println("所有任务执行完毕");
    }

    static class AccumulationTask implements Callable<Integer> {

        private Integer num;

        public AccumulationTask(Integer num){
            this.num = num;
        }

        @Override
        public Integer call() throws Exception {
            LoggerUtil.split();
            LoggerUtil.printThread();
            LoggerUtil.println("子线程在进行计算");
            //Thread.sleep(3000);
            int sum = 0;
            for (int i = 0; i < num; i++) {
                sum++;
            }
            LoggerUtil.println("子线程在计算完成");
            Thread.sleep(3000);
            return sum;
        }
    }
}
